package cn.gok.web;

import cn.gok.entity.TMaintainDormitory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;

import cn.gok.entity.TStudent;
import cn.gok.service.MaintainService;
import cn.gok.service.impl.MaintainServiceImpl;
import cn.gok.util.R;
import cn.hutool.json.JSONUtil;
import lombok.SneakyThrows;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

@WebServlet("/maintain")
public class MaintainServlet extends HttpServlet {
    private MaintainService maintainService=new MaintainServiceImpl();

    @SneakyThrows
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String action = req.getParameter("action");
        switch (action){
            case "addMaintain":addMaintain(req,resp);
            case "queryInfo":queryInfo(req,resp);
        }
    }
   public static List<String >suffixesImage=new ArrayList<>();//定义集合，存储图片格式名
    static {
        suffixesImage.add(".png");
        suffixesImage.add(".jpg");
        suffixesImage.add(".gif");
        suffixesImage.add(".jpeg");
        suffixesImage.add(".bmp");
    }
    //学生添加报修信息
    public void addMaintain(HttpServletRequest req, HttpServletResponse resp) throws FileUploadException {
        //获取commons.fileuplod工具提供工厂对象
        FileItemFactory factory=new DiskFileItemFactory();
        //根据工厂对象获取一个文件上传的fileupload对象
        ServletFileUpload fileUpload = new ServletFileUpload(factory);
        //限制大小5m
        fileUpload.setFileSizeMax(1024*1024*5);
        //解析request请求,request请求中既有字符串数据，又有上传的多媒体文件数据（text,png,jpg,mp4）

        Map<String, List<FileItem>> parameterMap =null;

        try {
            parameterMap = fileUpload.parseParameterMap(req);

            //获取宿舍报修文本信息
            List<FileItem> fileItems = parameterMap.get("desc1");
            String desc1 = new String(fileItems.get(0).get(), "utf-8");
            //获取报修上传的图片
            List<FileItem> fileItems1 = parameterMap.get("file");
            FileItem fileItem=fileItems1.get(0);
            //判断用户提交的是否为图片
            //获取图片的名字

            String name = fileItem.getName();

            //获取图片的后缀名
            String substring = name.substring(name.lastIndexOf("."));
            //判断
            boolean contains = suffixesImage.contains(substring);
            if (!contains){
                //如果图片格式不符合
                resp.getWriter().println(JSONUtil.toJsonStr(R.fail("上传失败，请上传正确的图片格式")));
                return;
            }

            //重新生成图片名
            String newImageName = UUID.randomUUID().toString()+substring;


            //生成图片存储的路径
            String contextPath = req.getSession().getServletContext().getRealPath("");
            File file = new File(contextPath + File.separator + "tMaintainDormitory");



            //将图片输出到指定的路径
            fileItem.write(new File(contextPath + File.separator + "tMaintainDormitory" +
                    File.separator + newImageName));

            //将基本信息存入数据库
            TMaintainDormitory tMaintainDormitory1=new TMaintainDormitory();
            TStudent student = (TStudent) req.getSession().getAttribute("student");
            tMaintainDormitory1.setId(student.getStuId());
//            tMaintainDormitory1.setDorId();
            tMaintainDormitory1.setDesc1(desc1);
            tMaintainDormitory1.setImageUrl(newImageName);
            tMaintainDormitory1.setCreateTime(new Date());
            R r = maintainService.addMaintain(tMaintainDormitory1);
            resp.getWriter().println(JSONUtil.toJsonStr(r));


        }
        catch (FileUploadException | UnsupportedEncodingException e){
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }


    }


    public void queryInfo(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setHeader("Content-type", "application/json;charset=utf-8");
        resp.setContentType("application/json;charset=utf-8");

        int stuId = ((TStudent)req.getSession().getAttribute("student")).getStuId();
        int state = Integer.parseInt(req.getParameter("state"));
        int currPage = Integer.parseInt(req.getParameter("currPage"));
        int pageSize = Integer.parseInt(req.getParameter("pageSize"));

        R r = maintainService.queryInfo(stuId, state, currPage, pageSize);

        resp.getWriter().println(JSONUtil.toJsonStr(r));


    }
}
